<!--
 - Copyright 2022. Huawei Technologies Co., Ltd. All rights reserved.

 - Licensed under the Apache License, Version 2.0 (the "License");
 - you may not use this file except in compliance with the License.
 - You may obtain a copy of the License at

 -   http://www.apache.org/licenses/LICENSE-2.0

 - Unless required by applicable law or agreed to in writing, software
 - distributed under the License is distributed on an "AS IS" BASIS,
 - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 - See the License for the specific language governing permissions and
 - limitations under the License.
 -->

<!-- 首页 -->
<template>
  <div>
    <HeadLine :headName="$t('BDT_fascialgun_firmware_upgrade')" @backClick="backClick" />
    <div class="upgrade_container" :style="style">
      <div class="upgrade_container_progress" v-if="checkUpdate">
        <CircleProgress ref="circleProgress" class="progress" :canvasWidth="canvasWidth" :strokeWidth="strokeWidth" :centerImage="centerImage">
        </CircleProgress>
      </div>
      <div class="device_line" v-else>
        <img class="device_img" :class="{'rtl-l': $rtl}" src="@/assets/image/device.png">
      </div>
      <span class="progress_title" :class="{'rtl-l': $rtl}">{{ progressTitle }}</span>
      <VersionModule :info="versionsNews" v-if="versionsNews.show" @versionClick="versionClick(1)" />
      <VersionModule :info="versionsCurrent" v-if="versionsCurrent.show" @versionClick="versionClick(2)" />
      <div class="version_btn">
        <button @click="btnClick" class="btn" :disabled="checkUpdate" :class="{gary: checkUpdate, 'rtl-l': $rtl}">检查更新</button>
      </div>
    </div>
    <ConfirmModule v-if="showConfirm" :confirmObj="confirmObj" @showConfirm="showConfirm=false" />
    <Notify v-if="notifyShow" :tpi="notifyText" />
  </div>
</template>
<script>
import HeadLine from "@/components/HeadLine";
import CircleProgress from "../components/CircleProgress";
import VersionModule from "../components/VersionModule";
import ConfirmModule from "../components/ConfirmModule";
import Notify from "../components/Notify";
import { mapState, mapMutations } from 'vuex';

export default {
  components: {
    HeadLine,
    CircleProgress,
    VersionModule,
    ConfirmModule,
    Notify
  },
  data() {
    return {
      canvasWidth: 25 * window.rem,
      strokeWidth: 2.4 * window.rem,
      versionsCurrent: {
        show: true,
        title: "当前版本",
        msg: "获取中",
        isNew: false,
        versionIconShow: true
      },
      versionsNews: {
        show: true,
        title: "新版本",
        msg: "1.0.1",
        isNew: true,
        versionIconShow: true
      },
      style: {
        marginTop: (px2rem(window.topHeight) + 5.6) + 'rem'
      },
      progressTitle: "正在检查...",  //正在检查...    已是最新版本    发现新版本
      centerImage: require('@/assets/image/device.png'),
      haveNewVersion: true,  // 是否有新版本
      isUpdateCompelete: '0',  // 0--未进行更新操作   1--更新页点击取消返回   2--更新完成返回
      cancelCheck: false, //取消检查
      confirmObj1: {
        title: "提示",
        titleAlign: true,
        tips: "当前设备蓝牙未开启,请开启蓝牙后重试",
        tipsTextCenter: true,
        showCancelButton: false,
        cancelButtonText: '',
        confirmButtonText: '知道了'
      },
      confirmObj: {
        title: "提示",
        titleTextCenter: true,
        tips: '请确认一下问题后，再重新操作：',
        tipsTextCenter: false,
        showCancelButton: false,
        cancelButtonText: '',
        confirmButtonText: '知道了',
        questionList: ['请确认手机蓝牙已开启', '确保设备电量充足开启', '确保手机离设备1米之内']
      },
      showConfirm: false,
      notifyShow: false,
      notifyText: '当前网络连接不稳定，建议更换网络或稍后重试。',
      checkUpdate: false,
      bluetoothLineCount: 0,
      bluetoothAdapterState: false,//检查手机蓝牙状态
    }
  },
  computed: {
    ...mapState(['connected', 'storeModeList', 'modeIndex', 'connectStatus', 'deviceId', 'gearOptionList', 'timerOptionList'])
  },
  watch: {
    connected() {
      this.assignValue();
    },
    modeIndex() {
      this.assignValue();
    },
    bluetoothAdapterState:function(val){
      // 如果蓝牙开启状态
      if(val){
        this.registerBlueStateServer();
      }
    }
  },
  mounted() {
    // 开始连接蓝牙
    this.startBluetoothConnection();
  },
  methods: {
    // 蓝牙连接
    startBluetoothConnection() {
      let self = this;
      // 重置蓝牙开启状态
      this.bluetoothAdapterState = false;
      this.bluetoothLineCount = 0;
      this.checkUpdate=true;
      this.progressTitle = '正在检查...';
      this.$refs['circleProgress'].initMethod(5000)
      self.jsInjection.setTitle("跑步机");
      let id = self.jsInjection.getDeviceId();
      this.getDeviceId(id);
      console.info("deviceId: " + self.deviceId);
      // 判断手机蓝牙状态
      window.getBluetoothAdapterState = self.getBluetoothAdapterState;
      self.jsInjection.getBluetoothAdapterState("getBluetoothAdapterState");
    },
    getBluetoothAdapterState: function (response) {
      console.info("getBluetoothAdapterState = " + response);
      let result = JSON.parse(response);
      if (result && result.errCode === 0 && result.available) {
        this.bluetoothAdapterState = true;
        this.changeConnectStatus('0');
        console.info("getBluetoothAdapterState bleStatus = " + this.bluetoothAdapterState);
      } else {
        this.getBlueErrorConfirm();
      }
    },
    // 获取手机蓝牙适配器状态: 获取状态失败
    getBlueErrorConfirm(){
      this.showConfirm=true;
      this.checkUpdate=false;
      this.progressTitle = '检查失败';
      this.confirmObj={
        title: "提示",
        titleTextCenter: true,
        tips: '请确认一下问题后，再重新操作：',
        tipsTextCenter: false,
        showCancelButton: false,
        cancelButtonText: '',
        confirmButtonText: '知道了',
        questionList: ['请确认手机蓝牙已开启', '确保设备电量充足开启', '确保手机离设备1米之内']
      }
    },
    // 开始注册监听服务和蓝牙连接状态
    registerBlueStateServer(){
       window.changeBleConnectionState = this.changeBleConnectionState;
        window.changeServiceDiscoverState = this.changeServiceDiscoverState;
        // 注册蓝牙连接的回调方法
        this.jsInjection.onBleConnectionStateChange("changeBleConnectionState");
        // 注册发现服务的回调方法
        this.jsInjection.onBleServicesDiscovered("changeServiceDiscoverState");
    },
    // 蓝牙连接状态回调
     changeBleConnectionState: function (response) {
      let result = JSON.parse(response);
      if (result && !result.connected) {
        // 已断开或连接超时显示：连接失败
        this.changeConnectStatus('0');
        this.bluetoothLineCount++;
        this.registerRestBLEConnection();
      }else{
        // 新老版本号出现
        this.changeConnectStatus('2');
      }
    },

    // 发现服务的回调方法
    changeServiceDiscoverState: function (response) {
      // 监听是否发现服务
      let result = JSON.parse(response);
      if (result && result.errCode == 0) {
        this.changeConnectStatus('2');
        window.getDeviceInfo = this.getDeviceInfo
        this.jsInjection.getDeviceInfo('getDeviceInfo');
      } else {
        // 异常处理
        this.bluetoothLineCount++;
        this.changeConnectStatus('0');
        this.registerRestBLEConnection();
      }
    },
    // 链接蓝牙
    registerCreateBLEConnection(){
      clearTimeout(this.createBLETimer);
      this.createBLETimer=setTimeout(()=>{
        this.jsInjection.createBleConnection(this.deviceId);
      },800)
    },
    // 重新开连接蓝牙
    registerRestBLEConnection(){
      // 先断开连接
      this.jsInjection.closeBleConnection();
      if(this.bluetoothLineCount<3){
        // 重新注册回调
        this.registerBlueStateServer();
        this.registerCreateBLEConnection();
      }else{
        this.getBlueErrorConfirm();
      }
    },
    
    //检查更新
    btnClick() {
      if (!this.checkDone) {
        return;
      };
      this.checkDone = false;
      this.isUpdateCompelete = '0';
      
      this.checkVersion();
    },
    versionClick(flag = 1) {
      let query = {};
      if (flag === 1) {
        query = { isNew: 1 }
      } else {
        query = { isNew: 0 }
      }
      this.$router.push({ path: '/versionView', query });
    },
    //版本检查
    checkVersion() {
      // 无新版本
      if (!this.haveNewVersion) {
        let timer = setTimeout(() => {
          this.progressTitle = "已是新版本";
          this.checkDone = true;
          clearTimeout(timer);
        }, 3000)
        return;
      }

      // 有新版本
      if (this.isUpdateCompelete == '2') { // 更新完成
        this.progressTitle = "已是新版本";
        this.checkDone = true;
        return;
      }

      // 未进行过更新操作，前往新版本页
      if (this.isUpdateCompelete == '0') {
        let timer = setTimeout(() => {
          this.addNewVersion();
          if (!this.cancelCheck) {
            // this.$router.push({
            //     path: '/versionView',
            //     query: {isNew: '1'}
            // });
          }
          clearTimeout(timer);
        }, 3000)
      } else {
        // 更新取消后直接展示新版本
        this.addNewVersion();
      }
    },

    //添加新版本信息
    addNewVersion() {
      this.checkDone = true;
      this.progressTitle = "发现新版本";
      let len = this.versions.length;
      //添加新版本之前先清空上一次的新版本信息
      this.versions = [this.versions[len - 1]];

      this.versions.unshift(
        {
          title: "新版本",
          msg: "1.1.0",
          img: require("@/assets/image/ic_public_right.svg"),
          isNew: '1'
        }
      );
    },
    //返回
    backClick() {
      this.cancelCheck = true;
      this.$router.push('/');
    },
    ...mapMutations([
      'changeConnectStatus',
      'getDeviceId'
    ]),
   

    modeClick() {
      this.$router.push('/modeView');
    },

    // 删除设备
    deleteDevice() {
      window.unbindDevice = this.unbindDevice;
      this.jsInjection.unbindDevice("unbindDevice");
    },

    // 删除设备 并关机
    unbindDevice(response) {
      if (response) {
        const { deviceId, globalData, directiveData, jsInjection, lastData } = this;
        jsInjection.writeDirective(deviceId, globalData.SERVICE_ID, globalData.CHARACTERISTIC_ID, directiveData.shutdown_directive);
        jsInjection.closeBleConnection(deviceId);
      }
    },

    // 获取设备信息
    getDeviceInfo(response) {
      let res = JSON.parse(response);
      let sn = '';
      if (res.errCode == 0) {
        sn = res.devInfo['sn'];
        log.info("request getDeviceInfo success", response);
        log.info("sn:", sn);
      } else {
        log.info("request getDeviceInfo err: " + response);
      }
    },

    // 数据切换
    assignValue() {
      const { strength, massage } = this.middleImg;
      if (!this.connected) {
        this.rightInfo.img = window.isDark ? massage.dark : massage.default;
        this.leftInfo.img = window.isDark ? strength.dark : strength.default;
        return;
      }

      // 运行时间、电池电量
      this.lastData.exerciseTime = '01:12:36';
      this.lastData.batteryLevel = '90';
      this.rightInfo.img = massage.on;
      if (this.modeIndex == 0) { // 默认模式下才可选择力度
        this.leftInfo.img = strength.on;
      } else {
        this.leftInfo.img = window.isDark ? strength.dark : strength.default;
      }
    },

    //重新连接
    reconnectClick() {
      this.changeConnectStatus('1');
      this.bluetoothConnection();
    },

    

    

    /**
     * 手机蓝牙状态回调：判断手机蓝牙是否打开，未打开则显示连接失败
     *
     * @param {Object} response 返回值
     */
    

    /**
     * 运行 暂停
     */
    runClick(val) {
      let data = '';
      const { deviceId, globalData, directiveData, jsInjection } = this;
      if (val == 0) {
        data = directiveData.pause_directive;
      } else {
        data = directiveData.start_directive;
      }
      jsInjection.writeDirective(deviceId, globalData.SERVICE_ID, globalData.CHARACTERISTIC_ID, data);
    },

    // 退出H5页面 并暂停设备
    backClick() {
      const { deviceId, globalData, directiveData, jsInjection, lastData } = this;
      jsInjection.writeDirective(deviceId, globalData.SERVICE_ID, globalData.CHARACTERISTIC_ID, directiveData.pause_directive);
      jsInjection.closeBleConnection(this.deviceId);
      BasicLib.container.exit();
      lastData.exerciseTime = '00:00:00';
      lastData.batteryLevel = '- -';
    }
  }
}
</script>
<style scoped>
.upgrade_container {
  display: flex;
  flex-direction: column;
  padding: 0 1.2rem;
  position: fixed;
  top: 0;
  left: 0;
  width: -webkit-fill-available;
  height: -webkit-fill-available;
  overflow: hidden scroll;
}

.upgrade_container_progress {
  height: 28.8rem;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 1.6rem;
}

.device_line {
  height: 21.2rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.progress_title {
  font-family: HarmonyOS_Sans_SC_Medium;
  font-size: 1.8rem;
  text-align: center;
  line-height: 2.5rem;
  margin-bottom: 3.2rem;
}

.device_img {
  width: 16.8rem;
  height: 16.8rem;
}

.version_btn {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  text-align: center;
  margin-bottom: 2.1rem;
  padding: 0 1.5rem;
}

.btn {
  height: 4rem;
  font-size: 1.6rem;
  font-family: HarmonyOS_Sans_SC_Medium;
  background: #fb6522;
  color: #fff;
  border: 0;
  border-radius: 2rem;
  width: 100%;
  max-width: 44.8rem;
}

.gary {
  opacity: 0.5;
}
</style>